<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/7/20
 * Time: 15:38
 */

namespace app\admin\model\frontend;


use app\admin\helper\SearchHelper;
use think\Config;
use think\Db;

class ApiM
{

    /**
     * 返回上一页 下一页ID
     * @return array|false|\PDOStatement|string|\think\Model
     */
    static public function getChapterPage(){
        $data = input('get.');
        $id = $data['id'];
        $novel_id = $data['novel_id'];
        $ac = $data['ac'];
        //是否最后一章
        $where = [
            'status' => 1,
            'novel_id' => $novel_id,
        ];
        $order = "";
        if ($ac == 'last') {
            $where['id'] = ['<',$id];
            $order = "created_at desc";
        }else if (($ac == 'next')) {
            $where['id'] = ['>',$id];
            $order = "created_at asc";
        }
        $count = Db::table('tb_novel_chapter')->where($where)->count();
        //存在则返回上一章或者下一章 不存在则返回本章
        if ($count) {
            return Db::table('tb_novel_chapter')->field('id')
                ->where($where)->order($order)->limit(1)->find()['id'];
        }
        return $id;
    }

    /**
     * 根据id获取小说
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    static public function getNovel($id) {
        $model = Db::table('tb_novel');
        $novel = $model->where('id',$id)->find();
        return $novel;
    }

    /**
     * 具体章节内容
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    static public function getChapterDetail($id){
        $where = [
            'status' => 1,
            'id' => $id
        ];
        $chapterM = Db::table('tb_novel_chapter');
        $chapterData = $chapterM->where($where)->find();
        $chapterData['all_count'] = countWords(htmlspecialchars_decode($chapterData['content']));
        //浏览量++
        Db::table('tb_novel_chapter')->startTrans();
        try{
            Db::table('tb_novel_chapter')->where('id',$id)->setInc('hits');
            Db::table('tb_novel_chapter')->commit();
        }catch (\Exception $e) {
            Db::table('tb_novel_chapter')->rollback();// 回滚事务
        }
        return $chapterData;
    }

    /**
     * 获取章节及卷名
     * @param $id
     * @return array
     */
    static public function getChapter($id){
        $res = [];
        $volumeM = Db::table('tb_novel_volume');
        $where = [
            'status' => 1,
            'novel_id' => $id
        ];
        $volumeData = $volumeM->where($where)->order('sort asc')->select();
        foreach ($volumeData as $v){
            $vID = $v['id'];
            $where['volume_id'] = $vID;
            $chapterM = Db::table('tb_novel_chapter');
            $chapterData = $chapterM->field('id,title')->where($where)->order('created_at asc')->select();
            $res[$v['id']]['v_title'] = $v['title'];
            $res[$v['id']]['v_chapter'] = $chapterData;
        }
        return $res;
    }

    /**
     * 获取小说列表
     * @param $taglist
     * @return false|\PDOStatement|string|\think\Collection
     */
    static public function getNovelList($taglist){
        $taglist = array_column($taglist,'name','code');
        $model = Db::table('tb_novel');
        $status_list = SearchHelper::getNovelStatusList();
        $data = $model->order('created_at desc')->select();

        foreach ($data as $k=>$v) {
            $data[$k]['novel_status_name'] = $status_list[$v['novel_status']];
            if (!empty($v['tags'])){
                $tags = explode(',',$v['tags']);
                $tagsName = [];
                foreach ($tags as $tag) {
                    if (isset($taglist[$tag]))
                        $tagsName[] = $taglist[$tag];
                }
                $data[$k]['tags_name'] = implode(',',$tagsName);
                //统计总字数
                $all_count = 0;
                $novel_id = $v['id'];
                $where = [
                    'status' => 1,
                    'novel_id' => $novel_id
                ];
                $chapterM = Db::table('tb_novel_chapter');
                $chapterData = $chapterM->field('content')->where($where)->select();
                if (!empty($chapterData)) {
                    foreach ($chapterData as $chapterDatum) {
                        $all_count = $all_count + countWords(htmlspecialchars_decode($chapterDatum['content']));
                    }
                }
                $data[$k]['all_count'] = $all_count;
            }
        }
        return $data;
    }

    /*
     * 当前用户是否喜欢过这篇文章
     */
    static public function articleLikeById($id){
        $model = Db::table('tb_like');
        if ($model->where(['realtion_id'=>$id,'ip'=>getIP()])->count())
            return 'like';
        return 'unlike';
    }

    /*
     * 当前用户是否喜欢过这篇文章
     */
    static public function articleLikes($id){
        $model = Db::table('tb_like');
        return $model->where(['realtion_id'=>$id])->count();
    }

    /*
   * 根据tag 获取相册status=1列表
   * */
    static public function listArticleByTag($tag){
        $model = Db::table('tb_article');
        return $model->where(['tag'=>$tag,'status'=>1])->order('updated_at desc')
            ->paginate(Config::get('app.page_info')['page_article_index'],false,[
                'type'     => 'bootstrap',
                'query' => [
                    'tag' => $tag
                ]
            ]);
    }

    /*
    * 根据tag 获取相册status=1列表
    * */
    static public function listAlbumByTag($tag){
        $model = Db::table('tb_album');
        return $model->where(['tag'=>$tag,'status'=>1])->order('updated_at desc')
            ->paginate(Config::get('app.page_info')['page_album_index'],false,[
                'type'     => 'bootstrap',
                'query' => [
                    'tag' => $tag
                ]
            ]);
    }


    /**
     * 根据id获取详细信息
     * @param $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    static public function getArticle($id){
        $model=Db::table('tb_article');
        //浏览量++
        Db::table('tb_article')->startTrans();
        try{
            Db::table('tb_article')->where('id',$id)->setInc('hits');
            Db::table('tb_article')->commit();
        }catch (\Exception $e) {
            Db::table('tb_article')->rollback();// 回滚事务
        }
        return $model->where('id',$id)->find();
    }

    /**
     * motto瀑布流
     * @return array
     */
    static public function getTimeFlow(){
        $page = input('get.page/d');
        $length = 5;
        $offset = ($page-1)*$length;
        $count = Db::table('tb_motto')->where('status',1)->count();
        $data = Db::table('tb_motto')->where('status',1)->limit($offset,$length)->order('updated_at desc')->select();
        foreach ($data as $k=>$v){
            $data[$k]['updated_at'] = date('Y-m-d H:i:s',$v['updated_at']);
        }
        return [
            'pages' => ceil($count/$length),
            'data' => $data,
        ];
    }

    /*
     * 获取blog最新时间轴
     * */
    static public function getTimeLineNew(){
        $model=Db::table('tb_motto');
        return $model->where('status',1)->limit(5)->order('updated_at desc')->select();
    }

    /*
     * 获取blog最新article
     * */
    static public function getArticleNew(){
        $model=Db::table('tb_article');
        return $model->alias('a')->field('a.*,b.name tag_name')
            ->join('tb_tag b','a.tag = b.code','left')
            ->where('a.status',1)->limit(8)->order('a.updated_at desc')->select();
    }

    /**
     * 获取最新说说
     * @return array|false|\PDOStatement|string|\think\Model
     */
    static public function getLastMotto(){
        $model = Db::table('tb_motto');
        return $model->where('status',1)->order('updated_at desc')->find();
    }

    /**
     * 获取主页配置
     * @return array|false|\PDOStatement|string|\think\Model
     */
    static public function getIndex(){
        $model = Db::table('tb_index');
        return $model->find();
    }

    /**
     * 获取相册
     * @return false|\PDOStatement|string|\think\Collection
     */
    static public function getAlbum(){
        $model = Db::table('tb_album');
        return $model->where('status',1)->group('tag')->order('updated_at desc')->select();
    }

}